#!/bin/bash

echo "=== HTTP服务器功能验证测试 ==="
echo "测试基于多Reactor + 线程池架构的HTTP服务器"
echo ""

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 检查必要文件
if [ ! -f "./http_server" ] || [ ! -f "./http_client_test" ]; then
    echo -e "${RED}错误：HTTP服务器程序未找到${NC}"
    echo "请先运行: make http_server http_client_test"
    exit 1
fi

echo -e "${YELLOW}1. 启动HTTP服务器（后台运行）...${NC}"
./http_server > http_server.log 2>&1 &
SERVER_PID=$!
echo "HTTP服务器进程ID: $SERVER_PID"

# 等待服务器启动
echo "等待服务器启动..."
sleep 3

# 检查服务器是否启动成功
if ! kill -0 $SERVER_PID 2>/dev/null; then
    echo -e "${RED}❌ HTTP服务器启动失败${NC}"
    cat http_server.log
    exit 1
fi

echo -e "${GREEN}✅ HTTP服务器启动成功${NC}"
echo ""

echo -e "${YELLOW}2. 运行基础功能测试...${NC}"

# 测试函数
test_endpoint() {
    local method="$1"
    local url="$2"
    local expected_code="$3"
    local description="$4"
    local data="$5"
    
    echo -n "测试 $description... "
    
    if [ "$method" = "GET" ]; then
        response=$(curl -s -w "%{http_code}" -o response_body.tmp "$url" 2>/dev/null)
    elif [ "$method" = "POST" ]; then
        response=$(curl -s -w "%{http_code}" -o response_body.tmp -X POST -d "$data" "$url" 2>/dev/null)
    fi
    
    http_code="${response: -3}"
    
    if [ "$http_code" = "$expected_code" ]; then
        echo -e "${GREEN}✅ 通过${NC} (HTTP $http_code)"
    else
        echo -e "${RED}❌ 失败${NC} (期望: HTTP $expected_code, 实际: HTTP $http_code)"
        if [ -f response_body.tmp ]; then
            echo "响应内容:"
            cat response_body.tmp
            echo ""
        fi
        return 1
    fi
}

# 基础GET测试
test_endpoint "GET" "http://localhost:8080/hello" "200" "Hello World API"
test_endpoint "GET" "http://localhost:8080/api/status" "200" "服务器状态API"
test_endpoint "GET" "http://localhost:8080/user/123" "200" "用户信息API"
test_endpoint "GET" "http://localhost:8080/" "200" "主页HTML"

# 查询参数测试
test_endpoint "GET" "http://localhost:8080/api/query?name=test&age=25" "200" "查询参数API"
test_endpoint "GET" "http://localhost:8080/api/headers" "200" "请求头API"

# POST测试
test_endpoint "POST" "http://localhost:8080/api/echo" "200" "POST回显API" "Hello HTTP Server"

# 404测试
test_endpoint "GET" "http://localhost:8080/notfound" "404" "404错误处理"

echo ""
echo -e "${YELLOW}3. 运行自动化客户端测试...${NC}"
./http_client_test > client_test.log 2>&1 &
CLIENT_PID=$!

# 等待客户端测试完成
wait $CLIENT_PID
CLIENT_EXIT_CODE=$?

if [ $CLIENT_EXIT_CODE -eq 0 ]; then
    echo -e "${GREEN}✅ 客户端测试完成${NC}"
else
    echo -e "${RED}❌ 客户端测试失败${NC}"
    echo "客户端测试日志:"
    cat client_test.log
fi

echo ""
echo -e "${YELLOW}4. 并发连接测试...${NC}"

# 并发测试
echo "启动10个并发curl请求..."
for i in {1..10}; do
    curl -s http://localhost:8080/api/status > /dev/null &
done

wait
echo -e "${GREEN}✅ 并发测试完成${NC}"

echo ""
echo -e "${YELLOW}5. 分析服务器日志...${NC}"

# 等待服务器处理完成
sleep 1

echo "=== 服务器运行情况 ==="
if [ -f "http_server.log" ]; then
    echo "HTTP连接统计:"
    grep -c "新连接建立" http_server.log && echo "个新连接" || echo "0个新连接"
    grep -c "连接关闭" http_server.log && echo "个连接关闭" || echo "0个连接关闭"
    
    echo ""
    echo "请求处理统计:"
    grep -c "GET " http_server.log && echo "个GET请求" || echo "0个GET请求"
    grep -c "POST " http_server.log && echo "个POST请求" || echo "0个POST请求"
    
    echo ""
    echo "SubReactor负载分析:"
    if grep -q "SubReactor-" http_server.log; then
        grep "SubReactor-" http_server.log | \
        awk -F'SubReactor-' '{print $2}' | \
        awk -F']' '{print $1}' | \
        sort | uniq -c | \
        awk '{print "SubReactor-" $2 ": " $1 " 次处理"}'
    else
        echo "未找到SubReactor处理记录"
    fi
else
    echo -e "${RED}未找到服务器日志文件${NC}"
fi

echo ""
echo -e "${YELLOW}6. 性能指标统计...${NC}"

# 简单的性能测试
echo "执行50个连续请求的性能测试..."
start_time=$(date +%s.%N)
for i in {1..50}; do
    curl -s http://localhost:8080/hello > /dev/null
done
end_time=$(date +%s.%N)

duration=$(echo "$end_time - $start_time" | bc)
rps=$(echo "scale=2; 50 / $duration" | bc)

echo "总耗时: ${duration}s"
echo "平均RPS: ${rps} 请求/秒"

echo ""
echo -e "${YELLOW}7. 清理测试环境...${NC}"

# 终止服务器
echo "终止HTTP服务器..."
kill $SERVER_PID 2>/dev/null
wait $SERVER_PID 2>/dev/null

# 清理临时文件
rm -f response_body.tmp client_test.log

echo ""
echo "==================== 测试总结 ===================="
echo -e "${GREEN}✅ HTTP服务器功能验证完成${NC}"
echo ""
echo "测试涵盖："
echo "- ✅ 基础HTTP方法 (GET, POST)"
echo "- ✅ 路由系统和参数处理"
echo "- ✅ 状态码和错误处理"
echo "- ✅ 并发连接处理"
echo "- ✅ 多Reactor架构验证"
echo "- ✅ 性能基准测试"
echo ""
echo "日志文件："
echo "- http_server.log: 服务器运行日志"
echo "- client_test.log: 客户端测试日志（如果存在）"
echo ""
echo -e "${GREEN}HTTP服务器已通过所有基础功能测试！${NC}"
echo -e "访问 http://localhost:8080 可以手动测试更多功能"